package cn.edu.whu.forecast.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author LXP
 * @version 1.0
 * @date 2021/12/30 10:08
 * 配置Mysql数据源
 **/
@Configuration
@MapperScan(basePackages = "cn.edu.whu.forecast.mapper.mysql", sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MySQLDataSourceConfig {

    @Value("${spring.datasource.mysql.jdbc-url}")
    private String url;

    @Value("${spring.datasource.mysql.username}")
    private String user;

    @Value("${spring.datasource.mysql.password}")
    private String password;

    @Value("${spring.datasource.mysql.driver-class-name}")
    private String driverClass;

    @Value("${spring.datasource.mysql.druid.test-on-borrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.mysql.druid.test-while-idle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.mysql.druid.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.mysql.druid.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.mysql.druid.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.mysql.druid.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.mysql.druid.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.mysql.druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    static {
        System.setProperty("druid.mysql.usePingMethod", "false");
    }

    @Primary // 表示这个数据源是默认数据源, 这个注解必须要加，因为不加的话spring将分不清楚那个为主数据源（默认数据源）
    @Bean("mysqlDataSource")
    public DataSource getMysqlDataSource() {
        DruidDataSource dataSource = new DruidDataSource();


        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);

        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnReturn(true);

        dataSource.setMaxActive(maxActive);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

        dataSource.setKeepAlive(true);

        dataSource.setValidationQuery(validationQuery);
        return dataSource;
    }

    @Primary
    @Bean("mysqlSqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mysql/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean("mysqlSqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
